package cn.fintecher.pangolin.service.dataimp.task;

import cn.fintecher.pangolin.common.enums.UserStatus;
import cn.fintecher.pangolin.entity.elastic.BaseCase;
import cn.fintecher.pangolin.entity.elastic.DistributeModel;
import cn.fintecher.pangolin.entity.mysql.CaseInfo;
import cn.fintecher.pangolin.entity.mysql.Principal;
import cn.fintecher.pangolin.entity.mysql.User;
import cn.fintecher.pangolin.service.dataimp.elastic.BaseCaseElastic;
import cn.fintecher.pangolin.service.dataimp.model.ImportDistributeModel;
import cn.fintecher.pangolin.service.dataimp.repository.CaseInfoRepository;
import cn.fintecher.pangolin.service.dataimp.repository.PrincipalRepository;
import cn.fintecher.pangolin.service.dataimp.repository.UserRepository;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 20:22 2019/11/5
 */

@Service("importDistributeFuture")
public class ImportDistributeFuture {
    @Autowired
    private BaseCaseElastic baseCaseElastic;

    @Autowired
    private CaseInfoRepository caseInfoRepository;

    @Autowired
    private PrincipalRepository principalRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 多线程生成案件对象
     */
    @Async
    public CompletableFuture<ImportDistributeModel> generate(Row row, String batchNumber) {
        ImportDistributeModel importDistributeModel = new ImportDistributeModel();
        List<String> errors = new ArrayList<>();
        DistributeModel model = new DistributeModel();
        model.setBatchNumber(batchNumber);
        Cell cell0 = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
        cell0.setCellType(CellType.STRING);
        String caseNumber = cell0.getStringCellValue(); //案件编号
        if (StringUtils.isBlank(caseNumber)) {
            errors.add("第【" + (row.getRowNum() + 1) + "】行【案件编号】为空");
        } else {
            BoolQueryBuilder builder = new BoolQueryBuilder();
            builder.must(QueryBuilders.matchPhraseQuery("caseNumber.keyword", caseNumber));
            Iterable<BaseCase> iterable = baseCaseElastic.search(builder);
            if (!iterable.iterator().hasNext()) {
                errors.add("第【" + (row.getRowNum() + 1) + "】行【案件编号】为【" + caseNumber + "】的案件在系统中不存在");
            } else {
                CaseInfo caseInfo = caseInfoRepository.findByCaseNumber(caseNumber);
                if (Objects.nonNull(caseInfo) && Objects.nonNull(caseInfo.getCurrentCollector())) {
                    errors.add("第【" + (row.getRowNum() + 1) + "】行【案件编号】为【" + caseNumber + "】的案件已经分配");
                } else {
                    model.setCaseNumber(caseNumber);
                }
            }
        }
        Cell cell1 = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
        cell1.setCellType(CellType.STRING);
        String principalName = cell1.getStringCellValue(); //委托方名称
        if (StringUtils.isNotBlank(principalName)) {
            Principal principal = principalRepository.findByName(principalName);
            if (Objects.nonNull(principal)) {
                model.setPrincipalName(principalName);
                model.setPrincipalId(principal.getId());
            }
        }
        Cell cell2 = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
        cell2.setCellType(CellType.STRING);
        String personalName = cell2.getStringCellValue(); //客户姓名
        if (StringUtils.isNotBlank(personalName)) {
            model.setPersonalName(personalName);
        }
        Cell cell3 = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
        cell3.setCellType(CellType.STRING);
        String certificateNo = cell3.getStringCellValue(); //证件号
        if (StringUtils.isNotBlank(certificateNo)) {
            model.setCertificateNo(certificateNo);
        }
        Cell cell4 = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
        cell4.setCellType(CellType.STRING);
        String cardNo = cell4.getStringCellValue(); //卡号
        if (StringUtils.isNotBlank(cardNo)) {
            model.setCardNo(cardNo);
        }
        Cell cell5 = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
        cell5.setCellType(CellType.STRING);
        String overdueAmtTotal = cell5.getStringCellValue(); //委案金额
        if (StringUtils.isNotBlank(overdueAmtTotal)) {
            try {
                model.setOverdueAmtTotal(Double.parseDouble(overdueAmtTotal));
            } catch (Exception e) {
                errors.add("第【" + (row.getRowNum() + 1) + "】行【委案金额】格式错误,该字段格式为【0】或【0.0】");
            }
        }
        Cell cell6 = row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
        cell6.setCellType(CellType.STRING);
        String leftAmt = cell6.getStringCellValue(); //欠款金额
        if (StringUtils.isNotBlank(leftAmt)) {
            try {
                model.setLeftAmt(Double.parseDouble(leftAmt));
            } catch (Exception e) {
                errors.add("第【" + (row.getRowNum() + 1) + "】行【欠款金额】格式错误,该字段格式为【0】或【0.0】");
            }
        }
        Cell cell7 = row.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
        cell7.setCellType(CellType.STRING);
        String username = cell7.getStringCellValue(); //员工工号
        if (StringUtils.isBlank(username)) {
            errors.add("第【" + (row.getRowNum() + 1) + "】行【分案员工工号】为空");
        } else {
            User user = userRepository.findByUsername(username);
            if (Objects.isNull(user)) {
                errors.add("第【" + (row.getRowNum() + 1) + "】行【分案员工工号】为【" + username + "】的用户不存在");
            } else {
                if (user.getStatus().equals(UserStatus.LEAVE)) {
                    errors.add("第【" + (row.getRowNum() + 1) + "】行【分案员工工号】为【" + username + "】的用户已离职");
                } else {
                    model.setUsername(username);
                }
            }
        }
        importDistributeModel.setDistributeModel(model);
        importDistributeModel.setErrors(errors);
        return CompletableFuture.completedFuture(importDistributeModel);
    }
}
